import logging
from dataclasses import is_dataclass
from typing import Type, Dict, Any, Callable

from src.log.logger import setup_logger


class HandlerRegister:
    """Handler注册器"""
    
    _handlers: Dict[str, Dict[str, Callable]] = {}  # 存储所有handler方法
    _instances: Dict[str, Any] = {}  # 存储handler实例
    logger: logging.Logger = setup_logger("handle.handler_register")

    @classmethod
    def subscribe(cls, event_cls: Type) -> Callable:
        """订阅事件的装饰器
        
        Args:
            event_cls: 事件类
        """
        def decorator(func: Callable) -> Callable:
            if not is_dataclass(event_cls):
                raise ValueError(f"事件类 {event_cls.__name__} 必须是dataclass")
            
            # 获取事件主题
            topic = getattr(event_cls, 'topic', None)
            if not topic:
                raise ValueError(f"事件类 {event_cls.__name__} 必须有topic属性")
            
            # 注册handler方法
            cls._handlers.setdefault(topic, {})[func.__qualname__] = func
            cls.logger.info(f"注册handler方法: {func.__qualname__} -> {topic}")
            
            # 不再包装为异步函数，保持原始函数
            return func
            
        return decorator

    @classmethod
    def register(cls, target_cls: Type) -> Type:
        """注册handler类的装饰器
        
        Args:
            target_cls: 要注册的handler类
        """
        cls._instances[target_cls.__name__] = target_cls
        cls.logger.debug(f"注册handler类: {target_cls.__name__}")
        return target_cls 